import { ApiProperty, IntersectionType } from "@nestjs/swagger";
import { $Enums, User } from "@prisma/client";
import { Transform } from "class-transformer";
import { IsBoolean, IsEnum, IsOptional, IsString, Matches } from "class-validator";

import { QueryDto } from "@/core/dto/query.dto";

export class QueryUserDto
    extends IntersectionType(QueryDto)
    implements
        Partial<
            Pick<User, "realname" | "username" | "nickname" | "email" | "mobile" | "gender" | "channel" | "isDisabled">
        >
{
    @Transform(({ value }) => value.trim())
    @IsOptional()
    @IsString()
    @ApiProperty({
        example: "张三",
        description: "真实姓名",
        required: false
    })
    realname: string;

    @Transform(({ value }) => value.trim())
    @Matches(/^[a-zA-Z0-9_]+$/, { message: "账号名只能包含字母、数字、下划线" })
    @IsOptional()
    @IsString()
    @ApiProperty({
        example: "ikun",
        description: "账号名，只能包含字母、数字、下划线",
        required: false
    })
    username: string;

    @Transform(({ value }) => value.trim())
    @IsOptional()
    @IsString()
    @ApiProperty({
        example: "坤坤",
        description: "昵称",
        required: false
    })
    nickname: string;

    @Transform(({ value }) => value.trim())
    @IsOptional()
    @IsString()
    @ApiProperty({
        example: "11@qq.com",
        description: "邮箱",
        required: false
    })
    email: string;

    @Transform(({ value }) => value.trim())
    @IsOptional()
    @IsString()
    @ApiProperty({
        example: "13800138000",
        description: "手机号",
        required: false
    })
    mobile: string;

    @IsOptional()
    @IsEnum($Enums.Gender)
    @ApiProperty({
        example: "male",
        description: "性别",
        enum: $Enums.Gender,
        required: false
    })
    gender: $Enums.Gender;

    @IsOptional()
    @IsEnum($Enums.Channel)
    @ApiProperty({
        example: "pc",
        description: "渠道",
        enum: $Enums.Channel,
        required: false
    })
    channel: $Enums.Channel;

    @Transform(({ value }) => {
        if (value === "1" || value === "yes" || value === "true") return true;
        if (value === "0" || value === "no" || value === "false") return false;
        return value;
    }) // 在 QueryDto 中，参数是以 URL 中的查询参数携带，而 URL 都是字符串类型"false"/"true"，所以需要转换一下
    @IsOptional()
    @IsBoolean()
    @ApiProperty({
        example: "true",
        description: "是否禁用",
        required: false
    })
    isDisabled: boolean;
}
